package com.gitee.l0km.codegen.wsdl;

import java.io.CharArrayWriter;
import java.net.URI;
import java.util.List;

import javax.wsdl.Definition;
import javax.wsdl.Input;
import javax.wsdl.Output;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.AttributeExtensible;
import javax.wsdl.extensions.ExtensionRegistry;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.wsdl.xml.WSDLWriter;
import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.WSDL11ToAllAxisServicesBuilder;

import com.gitee.l0km.com4j.base.Assert;

public class WSDLUtilits {

	public static final Definition loadWSDL(String wsdlURI){
		try {
			WSDLFactory factory = WSDLFactory.newInstance();
			WSDLReader reader = factory.newWSDLReader();
			reader.setFeature("javax.wsdl.verbose", true);
			reader.setFeature("javax.wsdl.importDocuments", true);
			return reader.readWSDL(wsdlURI);
		} catch (WSDLException e) {
			throw new RuntimeException(e);
		}
	}

	public static final Definition loadWSDL(URI wsdlURI){
		return loadWSDL(wsdlURI.toString());
	}

	public static final String getWSDLString(Definition definition) {
		Assert.notNull(definition, "definition");
		try {
			WSDLFactory factory = WSDLFactory.newInstance();
			WSDLWriter writer = factory.newWSDLWriter();
			CharArrayWriter write = new CharArrayWriter(1024);
			writer.writeWSDL(definition, write);
			return write.toString();
		} catch (WSDLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
     * Read the WSDL file
     *
     * @param uri
     * @throws WSDLException
     */
    public Definition readInTheWSDLFile(final String uri) throws WSDLException {

        WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
        reader.setFeature("javax.wsdl.importDocuments", true);

        ExtensionRegistry extReg = WSDLFactory.newInstance().newPopulatedExtensionRegistry();
        extReg.registerExtensionAttributeType(Input.class,
                new QName(AddressingConstants.Final.WSAW_NAMESPACE, AddressingConstants.WSA_ACTION),
                AttributeExtensible.STRING_TYPE);
        extReg.registerExtensionAttributeType(Output.class,
                new QName(AddressingConstants.Final.WSAW_NAMESPACE, AddressingConstants.WSA_ACTION),
                AttributeExtensible.STRING_TYPE);
        reader.setExtensionRegistry(extReg);

        return reader.readWSDL(uri);        
    }

	public static final List<AxisService> createAxisService(final Definition wsdl4jDef) throws AxisFault{
	    WSDL11ToAllAxisServicesBuilder builder = new WSDL11ToAllAxisServicesBuilder(wsdl4jDef);
	    builder.setCodegen(false);
	    builder.setAllPorts(false);
	     return builder.populateAllServices();		
	}
}
